from aip import AipOcr
from project import Main
import os, shutil
import fnmatch

""" 韩泽旭的 APPID AK SK """
APP_ID = '25205305'
API_KEY = 'iqBV0uXMxR4qnekeORIqQmUN'
SECRET_KEY = 'AomX8ENhERe7jGzOI6aj5LFiujpdFhvh'

client = AipOcr(APP_ID, API_KEY, SECRET_KEY)

""" 读取图片 """


def fun(file_name, time):
    # 源文件
    src_file = Main.file_path + "/" + file_name
    # 正常文件
    normal = Main.result_path + "/IMAGE" + "/normal"
    # 失败文件
    wrong = Main.result_path + "/IMAGE" + "/wrong"
    # 失败日志
    log = Main.result_path + "/IMAGE" + "/wrong.txt"

    # txt文件
    target = Main.result_path + "/IMAGE" + "/txt"

    if not os.path.exists(normal):
        os.makedirs(normal)  # 创建路径
    if not os.path.exists(target):
        os.makedirs(target)  # 创建路径
    if not os.path.exists(wrong):
        os.makedirs(wrong)  # 创建路径

    try:
        image = open(src_file, 'rb').read()
        options = {}
        options["detect_direction"] = "true"

        result = {}
        if time < 980:
            result = client.basicAccurate(image, options)
        else:
            result = client.basicGeneral(image, options)
        words = result['words_result']

        new_txt_name = ''
        if fnmatch.fnmatch(file_name, '*.jpeg') or fnmatch.fnmatch(file_name, '*.JPEG'):
            new_txt_name = file_name[:-5] + '.txt'
        else:
            new_txt_name = file_name[:-4] + '.txt'
        word_to_txt = target + "/" + new_txt_name

        with open(word_to_txt, "a") as file:  # 只需要将之前的”w"改为“a"即可，代表追加内容
            for line in words:
                file.write(line['words'] + "\n")

    except BaseException as e:
        shutil.move(src_file, wrong + "/")

        f = "wrong.txt"
        with open(log, "a") as file:  # "a"代表追加内容
            file.write(file_name + " " + repr(e) + "\n")

    else:
        shutil.move(src_file, normal + "/")
